import React from 'react'

import ReportContent from "../../components/Report";
import {secs2time, ts2time} from "../../utils/utils";
import moment from "moment";
import {fetchSpeedReportData} from "../../services/report";


function getDistance(lat1, lng1, lat2, lng2) {
  const radLat1 = lat1 * Math.PI / 180.0;
  const radLat2 = lat2 * Math.PI / 180.0;
  const a = radLat1 - radLat2;
  const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;// EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000;
  return s;
}

const handleDataFormat = (data, type) => {
  if (!data) return;
  let m = 0, prev_lat, prev_lng, prev_time;
  return data.map((item, idx) => {
    const {
      client_log_time,
      device_id,
      lat,
      lng,
    } = item;
    let _m = 0;
    let duration = 0;
    if (prev_lat) {
      _m = getDistance(prev_lat, prev_lng, lat, lng);
      duration = prev_time - client_log_time;
      m += _m
    }

    prev_lat = lat;
    prev_lng = lng;
    prev_time = client_log_time;
    const speed = duration ? Math.abs((_m / duration)).toFixed(4) : 0.00;
    return {
      key: idx,
      device_id,
      time: ts2time(client_log_time),
      // mileage: _m.toFixed(2),
      client_log_time,
      xy: `${lat}, ${lng}`,
      lat_lng: {lng, lat},
      speed,
      // mileage_total: m.toFixed(2),
    }
  })
};

const columnsDay = (handleTableClick) => ([
  {
    dataIndex: "device_id",
    title: "设备编号"
  },
  {
    dataIndex: "time",
    title: "定位时间"
  },
  {
    dataIndex: "speed",
    title: "速度"
  },
  {
    dataIndex: "xy",
    title: "位置",
    render: (text, record) => (
      <span>
            <a href="javascript:" onClick={handleTableClick(record.lat_lng)}>{text}</a>
          </span>
    ),
  },
]);


// # 设备编号  定位时间 速度 位置

const columnsDetail = (handleTableClick) => ([
  {
    dataIndex: "device_id",
    title: "设备编号"
  },
  {
    dataIndex: "time",
    title: "定位时间"
  },
  {
    dataIndex: "speed",
    title: "速度"
  },
  {
    dataIndex: "xy",
    title: "位置",
    render: (text, record) => (
      <span>
            <a href="javascript:" onClick={handleTableClick(record.lat_lng)}>{text}</a>
          </span>
    ),
  },
]);

const Speed = (props) => (
  <ReportContent {...props} title="速度报表" fetch={fetchSpeedReportData} handleDataFormat={handleDataFormat}
                 columnsDay={columnsDay} columnsDetail={columnsDetail} showChart={true}/>);


export default Speed;
